import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router/index.js'
const http = axios.create({
  baseURL: 'http://localhost:8888',
});

axios.defaults.timeout = 5000;
axios.defaults.withCredentials = false;

// 拦截器
http.interceptors.response.use((res) => {
  if (res.data?.token) {
    sessionStorage.setItem('token', res.data.token);
  }
  // 登录过期处理
  if (res.data.code === 401 || res.data.code===0) {
    ElMessage({
      message: res?.data?.message,
      type: 'error',
    });
    sessionStorage.removeItem('token');
    router.push({ name: 'loginview' });
  }

  return res.data;
});

axios.interceptors.request.use((config) => {
  console.log('添加token');
  // 需要再请求头上面统一携带token给后端传递
  const token = sessionStorage.getItem('token');
  if (token) config.headers.token = token;
  return config;
});
export default http;
